package com.generator.controller;


import com.generator.common.GeneratorParam;
import com.generator.entity.DatasourceConfig;
import com.generator.entity.TemplateConfig;
import com.generator.gen.GeneratorConfig;
import com.generator.service.DatasourceConfigService;
import com.generator.service.GeneratorService;
import com.generator.service.TemplateConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tanghc
 */
@RestController
@RequestMapping("/generator/generate")
public class GeneratorController {

    @Autowired
    private DatasourceConfigService datasourceConfigService;

    @Autowired
    private GeneratorService generatorService;
    @Autowired
    private TemplateConfigService templateConfigService;

    /**
     * 生成代码
     *
     * @param generatorParam 生成参数
     * @return 返回代码内容
     */
    @RequestMapping("/code")
    public ResponseEntity code(@RequestBody GeneratorParam generatorParam) {
        int datasourceConfigId = generatorParam.getDatasourceConfigId();
        if(!ObjectUtils.isEmpty(generatorParam.getGroupId())){
            List<TemplateConfig> templateConfigs = templateConfigService.listByGroupId(generatorParam.getGroupId().toString());
            if(!CollectionUtils.isEmpty(templateConfigs)){
                generatorParam.setTemplateConfigIdList(templateConfigs.stream().map(e->e.getId()).collect(Collectors.toList()));
            }

        }
        DatasourceConfig datasourceConfig = datasourceConfigService.getById(datasourceConfigId);
        GeneratorConfig generatorConfig = GeneratorConfig.build(datasourceConfig);
        return ResponseEntity.ok(generatorService.generate(generatorParam, generatorConfig));
    }

}
